# -*- coding: utf-8 -*-


from openerp import models
from openerp.osv import osv, fields, orm
from openerp import tools


class res_users_ext(orm.Model):
    ''' '''
    _inherit = 'res.users'

    # #############################
    # 扩展用户对应用户组的权限判断功能
    # 判断用户是否属于某些用户组
    @tools.ormcache(skiparg=2)
    def is_in_any_groups(self, cr, uid, group_ext_ids, context=None):
        """Checks whether user belongs to any of the given groups.

        :param str group_ext_ids: external IDs (XML IDs) of the groups.
           Must be provided in fully-qualified form (``module.ext_id``), as there
           is no implicit module to use..
        :return: True if the current user is a member of the group in the
           given external IDs (XML IDs), else False.
        """

        group_ext_ids = group_ext_ids.split(',')
        filterString = 'AND ( '
        for index in range(len(group_ext_ids)):
            group_ext_id = group_ext_ids[index]

            assert group_ext_id and '.' in group_ext_id, "External ID must be fully qualified"
            module, ext_id = group_ext_id.split('.')
            if index == 0:
                filterString += " (MODULE = '" + module + \
                    "' and NAME = '" + ext_id + "') "
            else:
                filterString += "or (MODULE = '" + module + \
                    "' and NAME = '" + ext_id + "') "
        sql = """SELECT count(1) as result FROM
                ir_model_data A JOIN res_groups_users_rel B ON A .res_id = B.gid
                WHERE   B.uid = """ + str(uid) + filterString + ')'
        # print 'check exists groups:',sql
        cr.execute(sql)
        resultInfo = cr.dictfetchone()

        if resultInfo['result'] > 0:
            return True
        else:
            return False

    ###########################
    #
    # 检查用户对某模型是否有导出权限
    #
    #@tools.ormcache(skiparg=2)
    def is_perm_export(self, cr, uid, model_name, context=None):
        if uid == 1:
            return True
        sql = """SELECT count(1) as result FROM ir_model_access ima
                  JOIN res_groups_users_rel rgur ON rgur.gid=ima.group_id
                  JOIN ir_model im ON im.id=ima.model_id
                  WHERE perm_export = TRUE AND rgur.uid=%s AND im.model='%s' LIMIT 1""" % (uid, model_name)
        cr.execute(sql)
        row = cr.dictfetchone()
        if row and row['result'] > 0:
            return True
        else:
            return False
